package homework.akkademo;

import akka.actor.*;
import akka.event.Logging;
import akka.event.LoggingAdapter;

public class LookupActor extends UntypedAbstractActor {


    LoggingAdapter log = Logging.getLogger(this.getContext().getSystem(), this);

    private ActorRef target = null;

    {
        // 将TargetActor 设定为LookupActor的子级，所以可以i直接指定路径，而不用绝对路径 /user/lookupActor/targetActor
        target = getContext().actorOf(
                Props.create(TargetActor.class, "targetActor")
        );
    }


    @Override
    public void onReceive(Object message) throws Throwable {
        if (message instanceof String) {
            // 我们向LookupActor 发送 find这个消息，然后通过上下文找到对应的ActorSelection,将这个消息转发给TargetActor
            if ("find".equals(message)) {
                ActorSelection as = getContext().actorSelection("targetActor");
                // ActorSelection 发送消息需要指定一个messageId,用来区分所查找的不同Actor(可能会查找到多个)
                // 消息发送后当前Actor会自动收到一个ActorIdentity，通过该对象的getActorRef方法得到ActorRef
                // ActorSelection不能保证ActorRef一定存在，所以要对ActorRef做非空判断
                // 也可以用通配符查询
                // 例如：/user/lookupActor/* 用于查找lookupActor下所有子级Actor
                // /user/lookupActor/target* 用于查找lookupActor下所有target开头的子级Actor
                as.tell(new Identify("A001"), getSelf());
            }
        } else if (message instanceof ActorIdentity) {
            ActorIdentity actorIdentity = (ActorIdentity) message;
            if (actorIdentity.correlationId().equals("A001")) {
                actorIdentity.getActorRef().ifPresent(
                        actorRef -> {
                            log.info("ActorIdentity:{}, ActorRef:{}", actorIdentity.correlationId(), actorRef);
                            actorRef.tell("hello target", getSelf());
                        }
                );
            }
        } else {
            unhandled(message);
        }

    }
}
